package com.zds.hj.poseidon.biz.dispatcher.credit.extend;


import com.zds.boot.common.context.ZDSContext;
import com.zds.boot.dispatch.comm.constants.DispatcherConstant;
import com.zds.boot.dispatch.comm.enums.ApproveStageEnum;
import com.zds.boot.dispatch.dto.BaseReqModel;
import com.zds.boot.dispatch.dto.DispatchModuleNodes;
import com.zds.boot.dispatch.dto.EngineDataHelperDto;
import com.zds.boot.dispatch.hole.HandlerDispatchEngineHelper;
import com.zds.boot.dispatch.spi.cep.EngineDataHandingHelperInterface;
import com.zds.hj.poseidon.biz.cba.hpp.domain.credit.service.layout.CreditApplyService;
import com.zds.hj.poseidon.facade.dto.hpp.credit.CreditInfoEntityDto;
import com.zds.zly.common.utils.EmptyChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * ==================================================
 * <p>
 * FileName: LiveCommHelper
 *
 * @author : shihongwei
 * @create 2019/8/30
 * @since 1.0.0
 * 〈功能〉：引擎数据处理类
 * ==================================================
 */
@Slf4j
@Component
public class EngineDataHandingHelper implements EngineDataHandingHelperInterface {


    @Resource
    private CreditApplyService creditApplyService;

    /**
     * ========================================
     *
     * @param reqModel
     * @return com.zds.appcore.facade.iteration2.approve.dto.EngineDataHelperDto
     * @throws
     * @方法说明 ： 验证在途数据（包括token 及其失效时操作， 在途步骤获取，业务产品占用公共产品记录等操作）
     * @author : shihongwei
     * @创建时间： 2019/12/4 17:02
     * ========================================
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public EngineDataHelperDto assessOtwOrder(BaseReqModel reqModel) {
        log.info("[模块调度引擎] 获取下一步 业务数据验证 >>> Params:{}", reqModel);
        if (ApproveStageEnum.CREDIT == reqModel.getStage()){
            //授信阶段的校验
            return creditDataValidate(reqModel);
        }
        return null;
    }


    /* *
     *========================================
     * @方法说明 ： 授信阶段判定
     * @author : shihongwei
     * @param reqModel
     * @param token
     * @param engineDataHelperDto
     * @return      com.zds.appcore.facade.iteration2.approve.dto.EngineDataHelperDto
     * @exception
     * @创建时间：     2019/12/3 22:01
     *========================================
     */
    private EngineDataHelperDto creditDataValidate(BaseReqModel reqModel) {
        // 获取在途订单
        EngineDataHelperDto engineDataHelperDto = new EngineDataHelperDto();
        CreditInfoEntityDto credit = creditApplyService.findCreditOnTransit(reqModel);
        // 获取最新的在途订单
        if (credit == null) {
            log.info("[模块调度引擎] 获取下一步 授信业务数据验证 无在途数据>>> user:{}", ZDSContext.get().getSeUserInfo().getId());
            // 没得在途订单，初始化订单
            CreditInfoEntityDto initDto = creditApplyService.init(reqModel);
            reqModel.setBizNo(initDto.getId());
            return engineDataHelperDto;
        }
        reqModel.setProductId(credit.getProductId().toString());
        reqModel.setBizNo(credit.getId());
        if (EmptyChecker.isEmpty(credit.getStep())) {
            return engineDataHelperDto;
        }
        String step = credit.getStep();
        DispatchModuleNodes nodeInfo = HandlerDispatchEngineHelper.getNodeInfo(credit.getProductId().toString(), reqModel.getModuleFlowType(), credit.getStage(), step, credit.getMerchantNo(), credit.getChannelNo());
        // 校验不可逆步骤后面的人工节点
        checkStepReverse(nodeInfo,credit.getProductId().toString(), reqModel, engineDataHelperDto);
        return engineDataHelperDto;
    }




    /**
     * @Author jingyh
     * @Description 校验自动非可逆步骤后是否为人工节点
     * @param engineDataHelperDto :
     * @return boolean
     **/
    private boolean checkStepReverse(DispatchModuleNodes nodeInfo, String productNo, BaseReqModel reqModel,EngineDataHelperDto engineDataHelperDto) {
        if (!nodeInfo.isReverse() && nodeInfo.isAuto()) {
            String nextStep = HandlerDispatchEngineHelper.getNextStepNotRun(productNo, reqModel.getModuleFlowType(), reqModel.getStage().code(), nodeInfo.getStep(), reqModel.getMerchantNo(), reqModel.getChannelNo());
            if (DispatcherConstant.END_STEP.equals(nextStep)) {
                // 下一步是自动节点，则返回
                return false;
            }
            DispatchModuleNodes nextStepInfo = HandlerDispatchEngineHelper.getNodeInfo(productNo,reqModel.getModuleFlowType(), reqModel.getStage().code(), nextStep, reqModel.getMerchantNo(), reqModel.getChannelNo());
            // 校验不可逆步骤后面的人工节点
            if (!nextStepInfo.isAuto()) {
                // 非自动节点
                engineDataHelperDto.setHasData(true);
                reqModel.setStep(nodeInfo.getStep());
                return true;
            }
        }
        return false;
    }

}
